package org.huang.sample15.service;

import org.huang.sample15.bo.Dept;
import org.huang.sample15.dao.DeptAnnoMapper;
import org.huang.sample15.dao.DeptXmlMapper;
import org.huang.sample15.util.DateUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.*;
import java.util.stream.Collectors;

@Service
public class DemoService {

    @Resource
    private DeptAnnoMapper deptAnnoMapper;

    @Resource
    private DeptXmlMapper deptXmlMapper;


    private ExecutorService executor = Executors.newFixedThreadPool(10);

    public List<Dept> listByIds(List<String> codes){
        if(CollectionUtils.isEmpty(codes)){
            return new ArrayList<>(0);
        }
        return codes.stream()
                .map(deptAnnoMapper::getOne)
                .collect(Collectors.toList());
    }

    public void testTimeout() {
        try {
            TimeUnit.MILLISECONDS.sleep(400);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public Dept getDeptById(Integer id){
        System.out.println("deptAnnoMapper="+deptAnnoMapper);
        System.out.println("deptXmlMapper="+deptXmlMapper);
        Dept dept = deptXmlMapper.selectByPrimaryKey(id);
        return Objects.nonNull(dept)? dept : deptAnnoMapper.getById(id);
    }

    public void testVoidMethod(Integer id) {
        System.out.println("deptAnnoMapper="+deptAnnoMapper);
        deptAnnoMapper.voidMethod(id);
        System.out.println("xxx");
    }

    public List<Dept> threadMethod(List<String> codes){
        List<Future<Dept>> list = new ArrayList<>();
        for (String code : codes) {
            FutureTask<Dept> futureTask = new FutureTask<>(() -> {
                Dept dept =  deptAnnoMapper.getOne(code);
                System.out.println(DateUtil.getNow());
                return dept;
            });
            list.add(futureTask);
            executor.submit(futureTask);
        }
        List<Dept> deptList = new ArrayList<>();
        for (Future<Dept> deptFuture : list) {
            try {
                Dept dept = deptFuture.get();
                deptList.add(dept);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return deptList;
    }


    public String staticMethod(){
        String now = DateUtil.getNow();
        return now;
    }

    protected String testPrivate() {
        System.out.println("xxxxxx");
        return "test";
    }

}
